import express from 'express';
import userCtrl from "../controller/userCtrl";
import {errorStatus} from '../plugins/status'
let router = express.Router()

export default function (app) {
  // 登录
  router.route("/login").post(userCtrl.login)
  // 注册
  router.route("/register").post(userCtrl.register)
  // 用户列表
  router.route("/users").get(userCtrl.userList)
  // 退出
  router.route("/logout").post(userCtrl.exit)
  // router.post("/logout",userCtrl.exit) 跟上面效果一样
  // 发送验证码
  router.post("/msgCode",userCtrl.sendMsgCode)
  // 上传图片
  router.route("/upload/image").post(userCtrl.addImages)
  // 删除图片
  router.route("/upload/image/:name").delete(userCtrl.removeImages)

  // 拦截器
  let intercept = (req,res,next) => {
    // console.log(req.url)
    // console.log(req.originalUrl)
    if (["/api/login","/api/register","/api/msgCode","/api/logout","/api/public/file/*"].includes(req.originalUrl)) {
      next()
    } else if (req.session.userInfo && req.session.userInfo.token == req.headers['Authorization']) {
      next()
    } else {
      errorStatus.RESULT.msg = "请登录"
      res.status(201).json(errorStatus.RESULT)
    }
  }
  app.use(intercept)
  app.use("/api",router)
}